<template>
    <div class="video-compress-container">
        <!-- 视频上传控件 -->
        <el-upload class="upload-demo" drag name="video" :data="{ resolution, bitrate }" action="#" :auto-upload="false"
            :show-file-list="false" :on-change="handleFileChange" :accept="videoTypes.join(',')">
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">
                拖拽视频到此或 <em>点击上传</em>
            </div>
            <template #tip>
                <div class="el-upload__tip">
                    支持 MP4/AVI/MOV 格式，建议大小不超过 500MB
                    <br>推荐分辨率 1280x720 或 1920x1080
                </div>
            </template>
        </el-upload>

        <!-- 压缩参数设置 -->
        <div class="compress-settings">
            <div class="param-item">
                <span class="param-label">目标分辨率</span>
                <el-input v-model="resolution" placeholder="例如：1280x720" style="width: 200px" />
            </div>

            <div class="param-item">
                <span class="param-label">视频码率</span>
                <el-select v-model="bitrate" style="width: 200px">
                    <el-option label="360P (360p)" value="280k" />
                    <el-option label="480p (480p)" value="560k" />
                    <el-option label="低清 (1000k)" value="1000k" />
                    <el-option label="标清 (2500k)" value="2500k" />
                    <el-option label="高清 (5000k)" value="5000k" />
                </el-select>
            </div>

            <el-button type="primary" :loading="isLoading" @click="startCompress">
                {{ isLoading ? '压缩中...' : '开始压缩' }}
            </el-button>
        </div>

        <!-- 视频预览区域 -->
        <div v-if="uploadedVideo" class="preview-area">
            <div class="video-pair">
                <div class="video-item">
                    <h4>原始视频 ({{ originalSize }})</h4>
                    <video controls :src="uploadedVideo" style="max-width: 500px; max-height: 300px;" />
                    <div class="video-info">
                        <span>时长：{{ originalDuration }}</span>
                        <span>格式：{{ originalFormat }}</span>
                    </div>
                </div>

                <div class="video-item">
                    <h4 v-if="compressedUrl">压缩结果 ({{ compressedSize }})</h4>
                    <template v-if="compressedUrl">
                        <video controls :src="compressedUrl" style="max-width: 500px; max-height: 300px;" />
                        <div class="video-info">
                            <span>压缩率：{{ compressionRatio }}%</span>
                            <span>处理时间：{{ processTimeStr }}毫秒</span>
                        </div>
                    </template>
                    <div v-else class="placeholder">
                        <el-icon :size="40">
                            <VideoCameraFilled />
                        </el-icon>
                        <p>压缩后的视频将在此显示</p>
                    </div>
                </div>
            </div>

            <!-- 结果操作 -->
            <div v-if="compressedUrl" class="result-actions">
                <el-link type="primary" :href="compressedUrl" target="_blank">
                    下载压缩视频
                </el-link>
                <el-button type="success" @click="copyLink">
                    复制下载链接
                </el-button>
            </div>
        </div>

        <!-- 进度提示 -->
        <el-dialog v-model="showProgress" title="压缩进度" width="30%" :close-on-click-modal="false" :show-close="false">
            <el-progress :percentage="progressPercent" :status="progressStatus" />
            <span class="progress-text">{{ progressText }}</span>
        </el-dialog>
    </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { UploadFilled, VideoCameraFilled } from '@element-plus/icons-vue'
import apis from '@/apis'

// 视频类型支持
const videoTypes = ['video/mp4', 'video/avi', 'video/quicktime']

// 响应式数据
const resolution = ref('640x360')
const bitrate = ref('2500k')
const uploadedVideo = ref(null)
const compressedUrl = ref(null)
const originalFile = ref(null)
const isLoading = ref(false)
const originalSize = ref(undefined)
const originalDuration = ref('00:00')
const compressedSize = ref(undefined)
const originalFormat = ref(undefined)
const processTimeStr = ref('')
const showProgress = ref(false)
const progressPercent = ref(0)
const progressText = ref('准备中...')
const progressStatus = ref(undefined)

// 计算属性
const compressionRatio = computed(() => {
    if (!originalFile.value || !compressedUrl.value) return 0
    const original = originalFile.value.size
    const compressed = compressedUrl.value.fileSize // 根据实际接口返回调整
    return ((1 - compressed / original) * 100).toFixed(1)
})

// 文件选择处理
const handleFileChange = async (file) => {
    if (!validateVideoType(file)) return
    originalFile.value = file.raw
    previewVideo(file.raw)
}

// 视频预览
const previewVideo = (file) => {
    const url = URL.createObjectURL(file)
    uploadedVideo.value = url

    // 获取视频元数据
    const video = document.createElement('video')
    video.preload = 'metadata'
    video.onloadedmetadata = () => {
        originalDuration.value = formatDuration(video.duration)
        originalFormat.value = file.name.split('.').pop().toUpperCase()
    }
    video.src = url
    originalSize.value = formatFileSize(file.size)
}

// 开始压缩
const startCompress = async () => {
    if (!validateParams()) return

    try {
        showProgress.value = true
        isLoading.value = true
        progressStatus.value = ''
        progressPercent.value = 0

        const formData = new FormData()
        formData.append('video', originalFile.value)
        formData.append('resolution', resolution.value)
        formData.append('bitrate', bitrate.value)

        // 调用压缩接口（修改后的版本）
        const response = await apis.utils.video.compress(formData, {
            onUploadProgress: e => {
                if (e.lengthComputable) {
                    progressPercent.value = Math.round((e.loaded / e.total) * 90) // 留10%给处理阶段
                }
            }
        })
        // 检查响应有效性
        if (!response || !response.downloadUrl) {
            throw new Error('无效的服务器响应')
        }
        // 处理业务逻辑状态码
        if (!response.status) {
            throw new Error(response.data.message || '视频处理失败')
        }

        // 更新最终进度
        progressPercent.value = 100
        progressText.value = '处理完成'
        progressStatus.value = 'success'

        // 使用解构赋值确保字段存在
        const {
            downloadUrl = '',
            fileSize = '',
            processTime = ''
        } = response || {}

        if (!downloadUrl) {
            throw new Error('缺少必要返回参数')
        }
        compressedSize.value = fileSize/1000 + 'KB'
        compressedUrl.value = downloadUrl
        processTimeStr.value = processTime
        ElMessage.success(`压缩完成，耗时 ${processTime}毫秒`)

    } catch (error) {
        console.error('压缩错误详情:', error)
        progressStatus.value = 'exception'
        progressText.value = '处理失败'

        // 更健壮的错误信息处理
        const errorMessage = error.response?.data?.message ||
            error.data?.message ||
            error.message ||
            '未知错误'

        ElMessage.error(`压缩失败: ${errorMessage}`)
    } finally {
        setTimeout(() => {
            showProgress.value = false
            isLoading.value = false
            progressPercent.value = 0
        }, 1500)
    }
}


// 修改后的验证方法
const validateParams = () => {
    try {
        const [width, height] = resolution.value.split('x').map(Number)
        if (isNaN(width) || isNaN(height) || width < 100 || height < 100) {
            throw new Error('分辨率需为 100x100 以上的有效数字')
        }

        if (!originalFile.value) {
            throw new Error('请先选择视频文件')
        }

        return true
    } catch (error) {
        ElMessage.error(error.message)
        return false
    }
}

// 文件类型验证
const validateVideoType = (file) => {
    if (!videoTypes.includes(file.raw.type)) {
        ElMessage.error('不支持的视频格式')
        return false
    }
    if (file.size > 500 * 1024 * 1024) {
        ElMessage.error('视频大小超过500MB限制')
        return false
    }
    return true
}

// 辅助函数
const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 B'
    const units = ['B', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(1024))
    return `${(bytes / Math.pow(1024, i)).toFixed(2)} ${units[i]}`
}

const formatDuration = (seconds) => {
    const mins = Math.floor(seconds / 60)
    const secs = Math.floor(seconds % 60)
    return `${mins.toString().padStart(2, '0')}:${secs.toString().padStart(2, '0')}`
}

const copyLink = async () => {
    try {
        await navigator.clipboard.writeText(compressedUrl.value)
        ElMessage.success('链接已复制到剪贴板')
    } catch {
        ElMessage.error('复制失败，请手动复制')
    }
}
</script>

<style scoped>
.video-compress-container {
    max-width: 1200px;
    margin: 20px auto;
    padding: 20px 30px;
}

.compress-settings {
    margin: 25px 0;
    display: flex;
    gap: 20px;
    align-items: center;
    flex-wrap: wrap;
}

.param-item {
    display: flex;
    align-items: center;
    gap: 10px;
}

.param-label {
    font-size: 14px;
    color: #606266;
}

.preview-area {
    margin-top: 30px;
}

.video-pair {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 30px;
}

.video-item {
    border: 1px solid #ebeef5;
    border-radius: 8px;
    padding: 15px;
    background: #f8f9fa;
}

.video-item h4 {
    margin: 0 0 15px 0;
    color: #303133;
}

.video-info {
    margin-top: 10px;
    display: flex;
    justify-content: space-between;
    font-size: 12px;
    color: #909399;
}

.placeholder {
    height: 300px;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    color: #c0c4cc;
}

.result-actions {
    margin-top: 20px;
    text-align: center;
}

.progress-text {
    display: block;
    margin-top: 10px;
    text-align: center;
    color: #909399;
}
</style>